package com.puhui.lib.base.dialog

import android.app.Activity
import android.content.DialogInterface
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.puhui.lib.R
import kotlinx.android.synthetic.main.loading_dialog.*

class LoadingDialog : BaseDialogFragment() {
    private var loadingText: String? = null
    private var showLoadingTv: Boolean = true
    private var isLoading = false  //是否正在显示状态

    override fun getLayoutRes(): Int = R.layout.loading_dialog

    override fun init(savedInstanceState: Bundle?) {
        if (!TextUtils.isEmpty(loadingText)) loadingTv.text = loadingText

        if (!showLoadingTv) loadingTv.visibility = View.GONE
    }

    fun show(activity: Activity?, text: String = "", canCancel: Boolean = true, showLoadingTv: Boolean = true) {
        activity?.let {
            if (isLoading) return@let
            synchronized(LoadingDialog::class.java) {
                if (!it.isFinishing && !isAdded) {
                    isLoading = true
                    isCancelable = canCancel
                    loadingText = text
                    this.showLoadingTv = showLoadingTv
                    super.show(activity)
                }
            }
        }
    }

    override fun onDismiss(dialog: DialogInterface) {
        isLoading = false
        super.onDismiss(dialog)
    }

    override fun getBackgroundRes() = R.color.transparent
}